<?php
/**
 * 群组权限中间表数据模型
 *
 * PHP version 5
 *
 * @package   SS
 * @author    Fee <Fee@shorigo.com>
 * @copyright 2015 SRG Inc.
 */
namespace Admin\Model;
use Think\Model;
class AdmingroupauthsModel extends Model {


    protected $tableName = 'sys_group_auths'; 

    /**
     * 设置主键
     *
     * @author Fee
     */
    protected $pk        = 'group_auth_id';

    /**
     * 自动验证
     *
     * @author Fee
     */
    protected $_validate = array(
        array('group_id',   'require', '群组ID不能为空'),
        array('auth_id',   'require', '权限ID不能为空'),
    );

    /**
     * 自动完成
     *
     * @author Fee
     */
    protected $_auto     = array(
        );

    /**
     * 获取群组下所有权限记录
     *
     * @param array $group_id 组权限
     *
     * @return array
     * @author Fee
     */
    public function getAuthsByGroup($group_id) {
        if(!empty($group_id)) {
            $rs = $this->where("group_id=" . $group_id)
                        ->field('auth_id')
                        ->select();
            if($rs) {
                $auths = array();
                foreach ($rs as $val) {
                   $auths[] = $val['auth_id'];
                }
                return $auths;
            } else {
                return array();
            }
        } else {
            return array();
        }
    }

    /**
     * 设置群组权限
     *
     * @param string $group_id   群组ID
     * @param array  $action_arr 权限数组
     *
     * @return array
     * @author Fee
     */
    public function setAuths($group_id, $action_arr) {
       
        /* 先删后加 */
        $rs = $this->where("group_id=" . $group_id)
                    ->delete();
        if(is_array($action_arr)){                         
            foreach($action_arr as $auth_id) {
                $auth_vo = array();
                $auth_vo['group_id'] = $group_id;
                $auth_vo['auth_id']  = remove_xss($auth_id);
                $this->add($auth_vo);
            }
        }
    }

    /**
     * 获取当前登录用户的群组权限
     *
     * @return array
     * @author Fee
     */
    public function getAdminGroupAuths() {

        $Admins = D("Admins");
        $groups = $Admins->getAdminAuthParam('group_id');

        if(empty($groups)) {
            return array();
        }

        $map = array();
        $map['group_id']  = array('in', $groups);
        
        $rs = $this->where($map)->field('auth_id')->select();
        
        if($rs) {
            $auths = array();
            foreach ($rs as $val) {
                $auths[] = $val['auth_id'];
            }
            return $auths;
        } else {
            return array();
        }
    }
}
?>